package com.soloyogame.anitoys.item.web.controller.front.product;

import com.alibaba.fastjson.JSON;
import com.soloyogame.anitoys.db.bean.Spec;
import com.soloyogame.anitoys.db.commond.*;
import com.soloyogame.anitoys.service.*;
import com.soloyogame.anitoys.util.cache.RedisCacheProvider;
import com.soloyogame.anitoys.util.constants.ManageContainer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by liam on 3/25/16.
 */

@Controller("productRepository")
public class ProductRepository {
    @Autowired
    private BusinessShippingService businessShippingService;
    @Autowired
    private BusinessService businessService;//品牌服务
    @Autowired
    private RedisCacheProvider redisCacheProvider;
    @Autowired
    private ProductService productService;//商品服务
    @Autowired
    private SpecService specService;
    @Autowired
    private CatalogService catalogService;
    @Autowired
    private ServiceGuaranteeService serviceGuaranteeService;//售后保障
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private BrandService brandService;//品牌服务
    @Autowired
    private BusinessRecommendService businessRecommendService;//店铺推荐商品服务
    @Autowired
    private TopPictureService topPictureService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private NavigationService navigationService;
    @Autowired
    private HotqueryService hotqueryService;

    private Catalog getCatalogByCatalogId(String catalogId) {
        Catalog childCatalog = new Catalog();
        childCatalog.setId(catalogId);
        childCatalog = catalogService.selectOne(childCatalog);
        Catalog parentCatalog = new Catalog();
        if (childCatalog != null) {
            parentCatalog.setId(childCatalog.getPid());
            parentCatalog = catalogService.selectOne(parentCatalog);
            List<Catalog> catalogList = new ArrayList<Catalog>();
            catalogList.add(childCatalog);
            parentCatalog.setChildren(catalogList);
        }
        return parentCatalog;
    }


    /**
     * 加载系统通知
     */
    public List<News> getNotices() {
        News news = new News();
        news.setOffset(0);
        news.setPageSize(7);
        return newsService.selectPlatNoticeList(news);
    }

    /**
     * 加载门户导航菜单
     */
    public List<Navigation> getNavigations() {
        Navigation nav = new Navigation();
        nav.setPosition("bottom");
        return navigationService.selectList(nav);
    }

    public List<Hotquery> getHotelQueryList() {
        return hotqueryService.selectList(new Hotquery());
    }

    /**
     * 加载平台的文章目录
     */
    public List<Catalog> getNewCatalogs() {
        Catalog c = new Catalog();
        c.setType("a");
        c.setPid("0");
        c.setShowInNav("y");
        List<Catalog> newCatalogs = catalogService.selectList(c);
        if (newCatalogs != null && newCatalogs.size() > 0) {
            for (int i = 0; i < newCatalogs.size(); i++) {
                Catalog item = newCatalogs.get(i);

                //加载此目录下的所有文章列表
                News news = new News();
                news.setCatalogID(item.getId());
                news.setStatus("y");
                List<News> newsList = newsService.selectPlatList(news);
                item.setNews(newsList);
            }
        }
        return newCatalogs;
    }

    public Product getProductByProductId(int productId) {
        String redisProductKey = productId + ManageContainer.product_info;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getProductByProductId, Error position: ProductRepository.java ,Method: getProductByProductId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            Product product = productService.selectproduct(productId);
            if(product==null){
            	 throw new NullPointerException("商品不存在！");
            }
            product.setSpecList(getSpecListByProductId(String.valueOf(productId)));
            saveToRedis(redisProductKey, product);
            return product;
        }
        Product product = JSON.parseObject(serializable.toString(), Product.class);
        if (product.getSpecList() == null || product.getSpecList().size() == 0) {
            product.setSpecList(getSpecListByProductId(String.valueOf(productId)));
            saveToRedis(redisProductKey, product);
        }
        return product;
    }

    private List<Spec> getSpecListByProductId(String productId) {
        Spec spec = new Spec();
        spec.setProductID(productId);
        return specService.selectList(spec);
    }

    private void refreshSpec(Spec spec, int productId) {
        String redisProductKey = productId + ManageContainer.product_xdkc + spec.getId();
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
            spec.setSpecStock(serializable.toString());
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not refreshSpec, Error position: ProductRepository.java ,Method: refreshSpec().Error Message:" + e.getMessage());
        }
    }

    public Spec getSpecByIds(int productId, String specId) {
        String redisProductKey = productId + ManageContainer.PRODUCT_SPEC + specId;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getSpecByIds, Error position: ProductRepository.java ,Method: getSpecByIds().Error Message:" + e.getMessage());
            serializable = null;
        }
        Spec spec;
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            spec = specService.selectById(specId);
            saveToRedis(redisProductKey, spec);
            return spec;
        }
        spec = JSON.parseObject(serializable.toString(), Spec.class);
        refreshSpec(spec, productId);
        return spec;
    }

    public Catalog getCatalogByCatalogId(String productId, String catalogId) {
        String redisProductKey = productId + ManageContainer.PRODUCT_SPEC + catalogId;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getCatalogByCatalogId, Error position: ProductRepository.java ,Method: getCatalogByCatalogId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            Catalog childCatalog = new Catalog();
            childCatalog.setId(catalogId);
            childCatalog = catalogService.selectOne(childCatalog);
            Catalog parentCatalog = new Catalog();
            if (childCatalog != null) {
                parentCatalog.setId(childCatalog.getPid());
                parentCatalog = catalogService.selectOne(parentCatalog);
                List<Catalog> catalogList = new ArrayList<Catalog>();
                catalogList.add(childCatalog);
                parentCatalog.setChildren(catalogList);
                saveToRedis(redisProductKey, parentCatalog);
            }
            return parentCatalog;
        }
        return JSON.parseObject(serializable.toString(), Catalog.class);
    }

    //加载商铺售后保障
    public ServiceGuarantee getServiceGuaranteeByBusinessId(String businessId) {
        String redisProductKey = businessId + ManageContainer.PRODUCT_SERVICEGUARANTEE;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getServiceGuaranteeByBusinessId, Error position: ProductRepository.java ,Method: getServiceGuaranteeByBusinessId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            ServiceGuarantee guarantee = new ServiceGuarantee();
            guarantee.setBusinessId(businessId);
            guarantee = serviceGuaranteeService.selectOne(guarantee);
            saveToRedis(redisProductKey, guarantee);
            return guarantee;
        }
        return JSON.parseObject(serializable.toString(), ServiceGuarantee.class);
    }

    public List<Attribute> getAttributeListByBusinessIdAndCatalogId(String businessId, String catalogId) {
        String redisProductKey = businessId + ManageContainer.PRODUCT_ATTRIBUTE_BUSINESS;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getAttributeListByBusinessIdAndCatalogId, Error position: ProductRepository.java ,Method: getAttributeListByBusinessIdAndCatalogId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        String emptyValue = "[]";
        if (serializable == null || serializable.toString().equals(nullValue) || serializable.toString().equals(emptyValue)) {
            Attribute attr = new Attribute();
            attr.setCatalogID(Integer.valueOf(catalogId));
            List<Attribute> attrList = attributeService.selectList(attr);
            //加载每个属性下的子属性列表
            if (attrList != null) {
                attr.setCatalogID(0);
                attr.setPid(0);//属性的
                for (Attribute item : attrList) {
                    attr.setPid(Integer.valueOf(item.getId()));
                    item.setAttrList(attributeService.selectList(attr));
                }
            }
            saveToRedis(redisProductKey, attrList);
            return attrList;
        }
        return JSON.parseArray(serializable.toString(), Attribute.class);
    }

    public List<BusinessRecommend> getBusinessRecommendByBusinessId(String businessId) {
        String redisProductKey = businessId + ManageContainer.PRODUCT_BUSINESSRECOMMENDS;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not get BusinessRecommendByBusinessId, Error position: ProductRepository.java ,Method: getBusinessRecommendByBusinessId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        String emptyValue = "[]";
        if (serializable == null || serializable.toString().equals(nullValue) || serializable.toString().equals(emptyValue)) {
            BusinessRecommend b = new BusinessRecommend();
            b.setBusinessId(businessId);
            b.setType(1);
            List<BusinessRecommend> businessRecommends = businessRecommendService.selectList(b);
            saveToRedis(redisProductKey, businessRecommends);
            return businessRecommends;
        }
        return JSON.parseArray(serializable.toString(), BusinessRecommend.class);
    }


    public List<Attribute> getAllAttributeByProductId(String productId) {
        String redisProductKey = productId + ManageContainer.PRODUCT_ATTRIBUTES;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getAllAttributeByProductId, Error position: ProductRepository.java ,Method: getAllAttributeByProductId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        String emptyValue = "[]";
        if (serializable == null || serializable.toString().equals(nullValue) || serializable.toString().equals(emptyValue)) {
            Attribute attribute = new Attribute();
            attribute.setProductId(Integer.valueOf(productId));
            List<Attribute> attributeList = attributeService.selectList(attribute);
            saveToRedis(redisProductKey, attributeList);
            return attributeList;
        }
        return JSON.parseArray(serializable.toString(), Attribute.class);
    }

    public Brand getBrandByBrandId(String brandId) {
        String redisProductKey = brandId + ManageContainer.PRODUCT_BRAND;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getBrandByBrandId, Error position: ProductRepository.java ,Method: getBrandByBrandId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            Brand brand = new Brand();
            brand.setId(brandId);
            brand = brandService.selectByIDs(Integer.valueOf(brand.getId()));
            saveToRedis(redisProductKey, brand);
            return brand;
        }
        return JSON.parseObject(serializable.toString(), Brand.class);
    }

    public Business getBusinessByBusinessId(String businessId) {
        String redisProductKey = businessId + ManageContainer.PRODUCT_BUSINESS;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getBusinessByBusinessId, Error position: ProductRepository.java ,Method: getBusinessByBusinessId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            Business business = businessService.selectById(businessId);
            saveToRedis(redisProductKey, business);
            return business;
        }
        return JSON.parseObject(redisCacheProvider.get(redisProductKey).toString(), Business.class);
    }

    public List<BusinessShipping> getShippingListByBusinessId(String businessId) {
        String redisProductKey = businessId + ManageContainer.PRODUCT_BUSINESSSHIPPING;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getShippingListByBusinessId, Error position: ProductRepository.java ,Method: getShippingListByBusinessId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        String emptyValue = "[]";
        if (serializable == null || serializable.toString().equals(nullValue) || serializable.toString().equals(emptyValue)) {
            Map<String, Object> mapBusinessShipping = new HashMap<String, Object>();
            mapBusinessShipping.put("businessId", businessId);
            List<BusinessShipping> businessShippings = businessShippingService.selectPrivence(mapBusinessShipping);
            saveToRedis(redisProductKey, businessShippings);
            return businessShippings;
        }
        return JSON.parseArray(redisCacheProvider.get(redisProductKey).toString(), BusinessShipping.class);
    }

    public TopPicture getTopPictureByBusinessId(String businessId) {
        String redisProductKey = businessId + ManageContainer.PRODUCT_TOPPICTURE;
        Serializable serializable;
        try {
            serializable = redisCacheProvider.get(redisProductKey);
        } catch (Exception e) {
            Logger.getGlobal().warning("Error: Can not getTopPictureByBusinessId, Error position: ProductRepository.java ,Method: getTopPictureByBusinessId().Error Message:" + e.getMessage());
            serializable = null;
        }
        String nullValue = "null";
        if (serializable == null || serializable.toString().equals(nullValue)) {
            TopPicture topPicture = new TopPicture();
            topPicture.setBusinessId(businessId);
            topPicture = topPictureService.selectOne(topPicture);
            saveToRedis(redisProductKey, topPicture);
            return topPicture;
        }
        return JSON.parseObject(redisCacheProvider.get(redisProductKey).toString(), TopPicture.class);
    }

    private void saveToRedis(final String redisProductKey, final Object object) {
        new Runnable() {
            @Override
            public void run() {
                redisCacheProvider.put(redisProductKey, JSON.toJSONString(object));
            }
        }.run();
    }
}
